package com.weido.nettyServer.core;

import com.weido.nettyServer.nettyMvc.NettyDispatcherServlet;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Created by chenli on 2019/11/11.
 */
@Component
public class MiNiTomcat {
    private static final Logger logger = LoggerFactory.getLogger(MiNiTomcat.class);
    @Value("${netty.server.port:8080}")
    private String port;//端口
    @Value("${netty.maxThreadNum:1024}")
    private String maxThreadNum;
    @Value("${netty.keepAlive:true}")
    private String keepAlive;
    @Value("${netty.servlet}")
    private String disPatcherServlet;

    public void start() throws InterruptedException {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workGroup = null;
        try {
            //Netty 封装了NIO reator
            //主线程
            bossGroup = new NioEventLoopGroup();
            //工作线程
            workGroup = new NioEventLoopGroup();
            //
            ServerBootstrap server = new ServerBootstrap();

            server.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    //子线程调用
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel client) throws Exception {
                            //客户端初始化处理
                            // 无锁化串行编程
                            //Netty对HTTP协议的封装，顺序有要求
                            client.pipeline().addLast("http-decoder",
                                    new HttpRequestDecoder()); // 请求消息解码器
                            client.pipeline().addLast("http-aggregator",
                                    new HttpObjectAggregator(65536));// 目的是将多个消息转换为单一的request或者response对象
                            client.pipeline().addLast("http-encoder",
                                    new HttpResponseEncoder());//响应解码器
                            client.pipeline().addLast("http-chunked",
                                    new ChunkedWriteHandler());//目的是支持异步大文件传输（）
                            //业务逻辑处理
                            client.pipeline().addLast(new MiNiTomcatHander());
                        }
                    })
                    //针对于主线程分配最大线程数量 --128
                    .option(ChannelOption.SO_BACKLOG, Integer.parseInt(maxThreadNum))
                    //针对于子线程配置
                    .childOption(ChannelOption.SO_KEEPALIVE, Boolean.parseBoolean(keepAlive));


            //启动服务
            ChannelFuture future = server.bind(Integer.parseInt(port)).sync();

            logger.info("Netty tomcat start " + port);
            //关闭服务
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    private class MiNiTomcatHander extends SimpleChannelInboundHandler<FullHttpRequest> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
            if (msg instanceof FullHttpRequest) {
                FullHttpRequest req = (FullHttpRequest) msg;

                /* 转交给自己实现的请求 */
                HttpRequest request = new HttpRequest(ctx, req);

                //自己实现
                HttpResponse response = new HttpResponse(ctx, req);
                //过滤器
                FilterChain filterChain = new FilterChain();

                filterChain.doFilter(request,response,filterChain);

                String url = request.getUrl();
                logger.info(url);
                getDisPatcherServlet().service(request, response);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            super.exceptionCaught(ctx, cause);
        }
    }

    public MiNiServlet getDisPatcherServlet() throws Exception {
        if (StringUtil.isNullOrEmpty(disPatcherServlet)) {
            throw new NullPointerException("MINIServlet is null!");
        }
        Class clazz;
        clazz = Class.forName(disPatcherServlet);
        Object o = clazz.newInstance();
        return (MiNiServlet) o;
    }
}

